package com.ctrlcar.giftrecord.controller;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctrlcar.giftrecord.pojo.User;
import com.ctrlcar.giftrecord.pojo.model.Result;
import com.ctrlcar.giftrecord.service.UserService;
import com.ctrlcar.giftrecord.utils.JwtUtil;
import com.ctrlcar.giftrecord.vo.UserVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:
 * @Description: 用户控制层
 * @DateTime: 2025-03-26 16:48
 **/

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private  UserService userService;

    @GetMapping
    public Result<User> getAllUsers(@RequestParam Integer userId) {
        return Result.success(userService.getById(userId));
    }


    /**
     *  登录和注册
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/loginAndRegister")
    public Result<UserVo> login(@RequestParam( "username") String username, @RequestParam( "password") String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        // 判断用户是否存在
        if (userService.getOne(queryWrapper) == null) {
            //不存在则注册
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
             userService.save(user);
            //生成返回用户token
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getUserId());
            claims.put("username", user.getUsername());
            String token = JwtUtil.genToken(claims);

            UserVo userVo = new UserVo();
            BeanUtil.copyProperties(user, userVo);
            userVo.setToken(token);
            return Result.success(userVo);
        } else {
            // 存在则判断密码是否正确
            User user = userService.getOne(queryWrapper);
            if (user.getPassword().equals(password)) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("username", user.getUsername());
                String token = JwtUtil.genToken(claims);

                UserVo userVo = new UserVo();
                BeanUtil.copyProperties(user, userVo);
                userVo.setToken(token);
                return Result.success(userVo);
            } else {
                return Result.error("用户已存在/密码错误");
            }
        }
    }
}
